﻿using System;
using System.Windows;
using GpgApi;
using Microsoft.Win32;
using WgpgCore;

namespace WgpgGUI
{
    public static class Encrypt
    {
        public static void File(Window owner, String filename)
        {
            if (String.IsNullOrEmpty(filename))
            {
                OpenFileDialog opendialog = new OpenFileDialog
                {
                    Title = L10N.T("encrypt_a_file"),
                    Multiselect = false,
                    CheckFileExists = true,
                    CheckPathExists = true,
                    Filter = L10N.T("filter_allfiles") + "|*.*"
                };

                if (opendialog.ShowDialog(owner) != true)
                    return;

                filename = opendialog.FileName;
            }

            EncryptionDialog encryptdialog = new EncryptionDialog(owner)
            {
                OriginalFileName = filename,
                EncryptedFileName = filename + ".wgpg"
            };

            if (encryptdialog.ShowDialog() != true)
                return;

            GpgEncrypt encrypt = new GpgEncrypt
            (
                armored: encryptdialog.ASCIIArmored,
                hideUserIds: encryptdialog.HideUserId,
                fileName: encryptdialog.OriginalFileName,
                encryptedFileName: encryptdialog.EncryptedFileName,
                signatureKeyId: encryptdialog.SignFile ? encryptdialog.SignatureKeyId : null,
                recipients: encryptdialog.UsePublicKey ? encryptdialog.PublicRecipients : null,
                cipherAlgorithm: encryptdialog.UseCipherAlgorithm ? encryptdialog.CipherAlgorithm : CipherAlgorithm.None
            );
            encrypt.AskPassphrase = GUIUtils.AskPassphrase(owner);

            TaskManager.Instance.Add(encrypt, "Encrypt " + filename);

            encrypt.ExecuteAsync(result =>
            {
                if (result.Status == GpgInterfaceStatus.Success)
                    CustomMessageBox.Show(owner, L10N.T("encryption_successfull"), L10N.T("encrypt_a_file"), MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
                else
                {
                    if (result.Message != GpgInterfaceMessage.Aborted)
                        CustomMessageBox.Show(owner, L10N.T("encryption_failed"), L10N.T("encrypt_a_file"), MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
                }
            });
        }
    }
}
